﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Linq;

namespace JustinAngel.Neurons.Framework.Helpers
{
    public static class StringHelper
    {
        public static string Remove(this string str, string StringToRemove)
        {
            return str.Replace(StringToRemove, string.Empty);
        }

        public static string AddSemiColomnToMalformedAscii(this string str)
        {
            var ReturnValue = str;

            var regex = new Regex(@"&#[0-9]+(?!;)");
            var matches = regex.Matches(str);

            var values = new List<string>();
            foreach (Match match in matches)
            {
                values.Add(match.Value);
            }
            values = values.Distinct().ToList();

            foreach (var value in values)
            {
                ReturnValue = ReturnValue.Replace(value, value + ";");
            }

            return ReturnValue;
        }

        private static string ConvertExtendedASCII(this string HTML)
        {
            string retVal = "";
            char[] s = HTML.ToCharArray();

            foreach (char c in s)
            {
                if (Convert.ToInt32(c) > 127)
                    retVal += "&#" + Convert.ToInt32(c) + ";";
                else
                    retVal += c;
            }

            return retVal;
        }

        public static string HtmlDecode(this string HTML)
        {
            return HttpUtility.HtmlDecode(HTML);
        }

        public static string CleanHtml(this string HTML)
        {
            return HTML
                .AddSemiColomnToMalformedAscii()
                //.ConvertExtendedASCII()
                .HtmlDecode()
                .Replace((char)145, (char)39) //  ‘  -> '
                .Replace((char)146, (char)39) //  ’  -> '
                .Replace((char)147, (char)34) //  “  -> "
                .Replace((char)148, (char)34) //  ”  -> "
                .Replace((char)150, (char)45) //  –  -> -
                .Replace((char)151, (char)45) //  —  -> -
                ;
        }
    }
}
